<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import DictionaryDialog from './component/DictionaryDialog.vue'
import { getDictionaryList, addDictionary, updateDictionary, deleteDictionaryType, refreshDictionaryCache } from '@/api/dictionary'

// 数据列表
const tableData = ref([])

// 分页参数
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 筛选参数
const searchForm = reactive({
  value: '',
  typeKey: ''
})

// 路由
const router = useRouter()

// 弹窗控制
const dialogVisible = ref(false)
const dialogMode = ref('add')
const currentRow = ref({})

// 获取数据列表
const getList = async () => {
  try {
    const params = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    const res = await getDictionaryList(params)
    tableData.value = res.list || []
    pagination.total = res.totals || 0
  } catch (error) {
    console.error('获取字典列表失败:', error)
    ElMessage.error('获取字典列表失败')
  } finally {
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    value: '',
    typeKey: ''
  })
  pagination.current = 1
  getList()
}

// 分页变化
const handlePageChange = (page) => {
  pagination.current = page
  getList()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.current = 1
  getList()
}

// 新增
const handleAdd = () => {
  dialogMode.value = 'add'
  currentRow.value = {}
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogMode.value = 'edit'
  currentRow.value = { ...row }
  dialogVisible.value = true
}

// 弹窗提交
const handleDialogSubmit = async (formData) => {
  try {
    if (dialogMode.value === 'add') {
      await addDictionary(formData)
      ElMessage.success('新增成功')
    } else {
      await updateDictionary({ ...formData, id: currentRow.value.id })
      ElMessage.success('编辑成功')
    }
    getList()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 跳转到字典详情页
const handleTypeKeyClick = (typeKey) => {
  router.push(`/system/dictionary-detail/${typeKey}`)
}

// 刷新字典缓存
const handleRefreshCache = async () => {
  try {
    await ElMessageBox.confirm(
      '系统缓存将在明天凌晨3:00自动刷新，确定要立即执行刷新操作吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await refreshDictionaryCache()
    ElMessage.success('缓存刷新请求已提交，系统将在明天凌晨3:00完成刷新')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('刷新缓存失败:', error)
      ElMessage.error('刷新缓存失败')
    }
  }
}

// 删除字典类型
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除字典类型 "${row.value}" 吗？删除后不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await deleteDictionaryType(row.typeKey)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<template>
  <div class="dictionary-container">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline>
        <el-form-item label="字典类型名称">
          <el-input
            v-model="searchForm.value"
            placeholder="请输入字典类型名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="字典类型键">
          <el-input
            v-model="searchForm.typeKey"
            placeholder="请输入字典类型键"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="card-header">
          <div>
            <el-button type="primary" @click="handleAdd">新增字典</el-button>
          </div>
          <div>
            <el-button type="warning" text @click="handleRefreshCache">
              <el-icon><Refresh /></el-icon>
              刷新缓存
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="120" />
        <el-table-column prop="value" label="字典类型名称" />
        <el-table-column prop="typeKey" label="字典类型键">
          <template #default="{ row }">
            <el-button 
              type="text" 
              @click="handleTypeKeyClick(row.typeKey)"
              style="color: #409eff; text-decoration: underline;"
            >
              {{ row.typeKey }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 弹窗 -->
    <DictionaryDialog
      :visible="dialogVisible"
      :mode="dialogMode"
      :data="currentRow"
      @update:visible="dialogVisible = $event"
      @submit="handleDialogSubmit"
    />
  </div>
</template>

<style scoped lang="scss">
.dictionary-container {
  padding: 20px;
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .pagination-wrapper {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
  }
}
</style>